package com.imooc.controller;

import com.imooc.pojo.BasicCode;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.pojo.Users;
import com.imooc.service.impl.UserServiceImpl;
import com.imooc.utils.IMoocJSONResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("api")
public class UserController {

    // 不用new 的，spring 自动管理对象的额创建和删除
    @Autowired
    private UserServiceImpl userService;


    // 返回之前的json包装类
    // 该路由用于用户的注册和登陆
    @PostMapping("/login")
    public IMoocJSONResult Login(@RequestBody Users user ) throws Exception {

        // 判断用户名和密码不能为空
        if(StringUtils.isBlank(user.getPwd()) ){
            return IMoocJSONResult.errorMsg("用户名或密码不能为空");
        }

        Users userResult = null ;

        if(userService.queryUseridIsExist(user.getUserID())){

            // 走登陆的逻辑
           userResult = userService.queryUserForLogin(user.getUserID(),user.getPwd());

           if(userResult == null){
               return IMoocJSONResult.errorMsg("用户名或密码不正确...");
           }

        }


        return IMoocJSONResult.ok(userResult);

    }


    @PostMapping("/register")
    public IMoocJSONResult register(@RequestBody Users users){

        // 需要先判断用户是不是已经存在了，如果用户已经存在了，就禁止用户注册
        if(!userService.queryUseridIsExist(users.getUserID())){

            Users users1 = userService.saveUser(users);
            if(users1 == null){
                return IMoocJSONResult.errorMsg("注册失败");
            }else {
                return IMoocJSONResult.ok(users1);
            }
        }else {
            return IMoocJSONResult.errorMsg("用户已经被注册过了");
        }

    }



    @GetMapping("/addBasicCode")
    public IMoocJSONResult addFriend(@RequestBody BasicCode basicCode){

       BasicCode users1 = userService.saveBasicCode(basicCode);
        if(users1 == null){
            return IMoocJSONResult.errorMsg("注册失败");
        }else {
            return IMoocJSONResult.ok(users1);
        }
    }





}
